package com.wonder.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.*;
import com.wonder.app.request.QingSfcInstockRequest;
import com.wonder.app.request.QingSfcOperpRequest;
import com.wonder.app.service.*;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class QingSfcInstockServiceImpl extends ServiceImpl<QingSfcInstockDao, QingSfcInstock> implements QingSfcInstockService {
    /** 日志 */
    private static final Logger _logger = LoggerFactory.getLogger(QingSfcInstockServiceImpl.class);


    @Autowired
    private MaterialService materialService;

    @Autowired
    private QingSfcInstockDao qingSfcInstockDao;

    @Autowired
    private QingSfcInstockDetailDao qingSfcInstockDetailDao;

    @Autowired
    private IVtuzxKingdeeService vtuzxKingdeeService;

    @Autowired
    private QingSfcInstockService qingSfcInstockService;

    @Autowired
    private  QingSfcInstockDetailService qingSfcInstockDetailService;

    @Autowired
    private SyncKingdeeOrderService syncKingdeeOrderService;
    @Autowired
    private QingSyncOrderService qingSyncOrderService;

    @Autowired
    private QingSyncOrderDetailService qingSyncOrderDetailService;

    @Autowired
    private QingSyncOrderDetailDao qingSyncOrderDetailDao;


    @Override
    public IPage<QingSfcInstock> selectList(QingSfcInstockRequest request, Page<QingSfcInstock> page) {
        LambdaQueryWrapper<QingSfcInstock> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (!VtuzxUtil.isEmpty(request.getSyncNo())){
            lambdaQueryWrapper.like(QingSfcInstock::getSyncNo,request.getSyncNo());
        }
        if (!VtuzxUtil.isEmpty(request.getMoBillNo())){
            lambdaQueryWrapper.like(QingSfcInstock::getMoBillNo,request.getMoBillNo());
        }
        if (!VtuzxUtil.isEmpty(request.getType())){
            lambdaQueryWrapper.like(QingSfcInstock::getType,request.getType());
        }
        if (request.getOrderTime() != null){
            Date[] orderDate = request.getOrderTime();
            if(orderDate.length>0)
                lambdaQueryWrapper.ge(QingSfcInstock::getOrderTime, orderDate[0]);
            if(orderDate.length==2)
                lambdaQueryWrapper.le(QingSfcInstock::getOrderTime,DateUtils.dateToStr(orderDate[1],"yyyy-MM-dd")+ " 23:59:59");

        }
        lambdaQueryWrapper.orderByDesc(QingSfcInstock::getOrderTime);
        Page<QingSfcInstock> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
        return selectPage;
    }
    @Override
    public Map<String, Object> getQingSfcInstockDetail(Map<String, Object> map) {
        String billNo = map.get("billNo").toString();
        QingSfcInstock qingsfcinstockform = qingSfcInstockDao.selectOne(new LambdaQueryWrapper<QingSfcInstock>()
                .eq(QingSfcInstock::getMoBillNo,billNo));
        List<QingSfcInstockDetail> qingsfcinstockList = qingSfcInstockDetailDao.selectList(new LambdaQueryWrapper<QingSfcInstockDetail>()
                .eq(QingSfcInstockDetail::getBillNo,billNo));
        Map<String,Object> data = new HashMap<>();
        data.put("data",qingsfcinstockform);
        data.put("dataList",qingsfcinstockList);
        return data;
    }

    @Override
    public AjaxResult<Object> importOrder(String userName, Long user_id, List<Map<String, Object>> map) throws Exception {
        if(map==null || map.size()==0) return AjaxResult.failed(MessageUtils.message("没有获取到数据,请检查模版sheet页"));
        Map<String,Object> orderMap = new HashMap<>();//key:制令单号(单据编号)val:单据头
        Map<String,Object> detailMap = new HashMap<>();//key:制令单号(单据编号) val:单据体集合
        List<String> orderNoList = new ArrayList<>();//客户订单号集合
        try {
            Map<String, Object> headRow = map.get(0);
            String djlxHd = String.valueOf(headRow.get("__EMPTY")).trim();
            String djrqHd = String.valueOf(headRow.get("__EMPTY_1")).trim();
            String zldhHd = String.valueOf(headRow.get("__EMPTY_2")).trim();
            String wlbmHd = String.valueOf(headRow.get("__EMPTY_3")).trim();
            String rkslHd = String.valueOf(headRow.get("生产入库单")).trim();
            String ckHd = String.valueOf(headRow.get("__EMPTY_4")).trim();
            String cwHd = String.valueOf(headRow.get("__EMPTY_5")).trim();
            String phHd = String.valueOf(headRow.get("__EMPTY_6")).trim();
            String bzHd = String.valueOf(headRow.get("__EMPTY_7")).trim();

            if (!"单据类型".equals(djlxHd) ||
                    !"单据日期".equals(djrqHd) ||
                    !"制令单号".equals(zldhHd) ||
                    !"物料编码".equals(wlbmHd) ||
                    !"入库数量".equals(rkslHd) ||
                    !"仓库".equals(ckHd) ||
                    !"仓位".equals(cwHd) ||
                    !"批号".equals(phHd) ||
            !"备注".equals(bzHd)) {
                return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
            }

        } catch (Exception e) {
            // 捕获所有异常并返回错误信息
            return AjaxResult.failed(MessageUtils.message("导入模版错误，请检查模版格式"));
        }


        //前期校验excel模板数据
        Boolean aBoolean = checkQingSfcInstock(userName, user_id, map);
        if (!aBoolean){
            throw new RuntimeException("模板数据校验未通过,请查看传单日志查看具体信息");
        }

        //订单同步开始
        String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"生产入库单");
        List<String> materialNoList = new ArrayList<>();
        List<String> stockNameList = new ArrayList<>();
        //先查询出物料和车间等信息
        for (Map<String,Object>  item:map){
            String orderNo = item.get("__EMPTY_2").toString();//制令单号
            if ("制令单号".equals(orderNo)){
                continue;
            }
            String materialNo = VtuzxUtil.getString(item,"__EMPTY_3");//物料编码
            if (!materialNoList.contains(materialNo)){
                materialNoList.add(materialNo);
            }

        }
        //根据物料编码查询物料名称等信息
        List<Map<String, Object>> materialList = materialService.getqingMaterialByNo(materialNoList);
        //将查询到的物料信息转成map
        Map<String, Object> materialToMap = changeMaterialToMap(materialList);
        for (Map<String,Object>  item:map){
            String orderNo = item.get("__EMPTY_2").toString();//制令单号
            if ("制令单号".equals(orderNo)){
                continue;
            }
            if(!orderNoList.contains(orderNo)){
                orderNoList.add(orderNo);
            }
            String orderType = VtuzxUtil.getString(item,"__EMPTY");//单据类型
            Integer OrderTime = VtuzxUtil.getInt(item,"__EMPTY_1");//单据日期

            String materialNo = VtuzxUtil.getString(item,"__EMPTY_3");//物料编码
            Double count = VtuzxUtil.getDouble(item,"生产入库单");//数量
            String stock= VtuzxUtil.getString(item,"__EMPTY_4");//仓库
            String location = VtuzxUtil.getString(item,"__EMPTY_5");//仓位
            String lot = VtuzxUtil.getString(item,"__EMPTY_6");//批号
            String beizhu = VtuzxUtil.getString(item,"__EMPTY_7");//备注

            QingSfcInstock qingSfcInstock = VtuzxUtil.getObject(orderMap,orderNo);
            if (null == qingSfcInstock){
                QingSfcInstock operp = new QingSfcInstock();
                operp.setMoBillNo(orderNo);
                operp.setOrderTime(conVerDate(OrderTime));
                operp.setType(orderType);
                operp.setSyncNo(tbbillNo);//同步单号
                orderMap.put(orderNo,operp);
            }
            //map中添加详情数据
            List<QingSfcInstockDetail> orderqingDetailList = VtuzxUtil.getObject(detailMap,orderNo);
            if (null == orderqingDetailList || orderqingDetailList.size() == 0){
                List<QingSfcInstockDetail> orderDetails = new ArrayList<>();
                QingSfcInstockDetail detail = new QingSfcInstockDetail();
                detail.setBillNo(orderNo);
                detail.setStock(stock);
                detail.setLocation(location);
                detail.setQty(count);
                detail.setLot(lot);
                detail.setRemark(beizhu);
                //查询规格等信息
                Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,materialNo);
                if (!VtuzxUtil.isEmpty(materialMap)){
                    detail.setMaterialNo(materialNo);
                    detail.setMaterialName(VtuzxUtil.getString(materialMap,"FNAME"));
                    detail.setSpecification(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
                    detail.setUnitName(VtuzxUtil.getString(materialMap,"unitName"));
                    detail.setUnitNo(VtuzxUtil.getString(materialMap,"unitNo"));
                }


                orderDetails.add(detail);
                detailMap.put(orderNo,orderDetails);
            } else {
                QingSfcInstockDetail detail = new QingSfcInstockDetail();
                detail.setBillNo(orderNo);
                detail.setStock(stock);
                detail.setLocation(location);
                detail.setQty(count);
                detail.setLot(lot);
                detail.setRemark(beizhu);
                //查询规格等信息
                Map<String,Object> materialMap = VtuzxUtil.getObject(materialToMap,materialNo);
                if (!VtuzxUtil.isEmpty(materialMap)){
                    detail.setMaterialNo(materialNo);
                    detail.setMaterialName(VtuzxUtil.getString(materialMap,"FNAME"));
                    detail.setSpecification(VtuzxUtil.getString(materialMap,"FSPECIFICATION"));
                    detail.setUnitName(VtuzxUtil.getString(materialMap,"unitName"));
                    detail.setUnitNo(VtuzxUtil.getString(materialMap,"unitNo"));
                }
                orderqingDetailList.add(detail);
                detailMap.put(orderNo,orderqingDetailList);
            }

        }
        //查询已经保存过的生产订单
        List<String> saveOrderNoList =  selectQingOperpByOrderNo(orderNoList);


        List<QingSyncOrderDetail> orderDetailList = new ArrayList<>();//需要保存到传单日志详情表中的数据
        for (String orderNo: orderNoList){
            //根据订单编号查询传单日志表
            QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
            qingSyncOrderDetail = new QingSyncOrderDetail();
            qingSyncOrderDetail.setOrderNo(orderNo);
            qingSyncOrderDetail.setBillNo(tbbillNo);
            qingSyncOrderDetail.setCreateTime(new Date());
            qingSyncOrderDetail.setUpdateTime(new Date());


            QingSfcInstock qingSfcInstock = VtuzxUtil.getObject(orderMap,orderNo);
            List<QingSfcInstockDetail> qingSfcInstockDetailList = VtuzxUtil.getObject(detailMap,orderNo);
            List<QingSfcInstockDetail> detailList = new ArrayList<>();
            detailList.addAll(qingSfcInstockDetailList);

            try {
                syncKingdeeOrderService.syncQingPrdInstock(qingSfcInstock, detailList,user_id);
                //数据库批量保存数据
                boolean saveBatch = saveQingBatchInstock(orderMap,detailMap,orderNoList,saveOrderNoList);
                qingSyncOrderDetail.setIsSuccess(true);

            } catch (Exception e){
                // 判断是否为重复导入
                boolean isRepeatImport = saveOrderNoList.contains(orderNo);
                //捕获异常删除已经保存的数据
                deleteQingSfcInstock(qingSfcInstock,qingSfcInstockDetailList, isRepeatImport);
                _logger.info(e.getMessage());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage(e.getMessage());

            }
            orderDetailList.add(qingSyncOrderDetail);
        }
        Map<String, Object> data = qingSyncOrderService.endQingSyncOrder(orderDetailList, tbbillNo);
        return AjaxResult.success(data);
    }

    private void deleteQingSfcInstock(QingSfcInstock qingSfcInstock, List<QingSfcInstockDetail> qingSfcInstockDetailList, boolean isRepeatImport) {
        List<Long> detailIdList = new ArrayList<>();

        for (QingSfcInstockDetail detail : qingSfcInstockDetailList) {
            Long id = detail.getId();
            if (id != null && !detailIdList.contains(id)) {
                detailIdList.add(id);
            }
        }

        if (isRepeatImport) {
            // 重复导入：只删除明细，不删除主表
            if (!detailIdList.isEmpty()) {
                qingSfcInstockDetailService.removeBatchByIds(detailIdList);
            }
        } else {
            // 全新导入：删除主表和所有明细
            qingSfcInstockService.removeById(qingSfcInstock.getId());
            if (!detailIdList.isEmpty()) {
                qingSfcInstockDetailService.removeBatchByIds(detailIdList);
            }
        }
    }




    //导入保存校验
    private boolean saveQingBatchInstock(Map<String, Object> orderMap, Map<String, Object> detailMap, List<String> orderNoList,List<String> saveOrderNoList) {

        List<QingSfcInstock> qingSfcInstockList = new ArrayList<>();
        List<QingSfcInstockDetail> detailList = new ArrayList<>();
        for (String orderNo : orderNoList){
            //如果之前上传过跳过循环
            if (saveOrderNoList.contains(orderNo)){
                List<QingSfcInstockDetail> sfcQingInstockDetailList = VtuzxUtil.getObject(detailMap,orderNo);
                detailList.addAll(sfcQingInstockDetailList);
            }else {

                QingSfcInstock qingSfcInstock = VtuzxUtil.getObject(orderMap, orderNo);
                List<QingSfcInstockDetail> sfcQingInstockDetailList = VtuzxUtil.getObject(detailMap, orderNo);
                qingSfcInstockList.add(qingSfcInstock);
                detailList.addAll(sfcQingInstockDetailList);
            }
        }
        boolean b = qingSfcInstockService.saveOrUpdateBatch(qingSfcInstockList);
        boolean r = qingSfcInstockDetailService.saveOrUpdateBatch(detailList);
        return b && r;
    }
    /**
     * 查询已经保存过的生产订单
     * @param orderNoList
     * @return
     */
    private List<String> selectQingOperpByOrderNo(List<String> orderNoList) {
        LambdaQueryWrapper<QingSfcInstock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(QingSfcInstock::getMoBillNo,orderNoList);
        List<QingSfcInstock> sfcQingOperpList = qingSfcInstockDao.selectList(queryWrapper);
        List<String>  saveOrderNoList = new ArrayList<>();
        if (!VtuzxUtil.isEmpty(sfcQingOperpList)){
            for (QingSfcInstock  qingSfcInstock : sfcQingOperpList){
                String billNo = qingSfcInstock.getMoBillNo();
                if (!saveOrderNoList.contains(billNo)){
                    saveOrderNoList.add(billNo);
                }
            }
        }

        return saveOrderNoList;
    }
    /**
     * Excel日期转换
     * @param times
     * @return
     */
    public Date conVerDate(int times){
        Calendar calendar = Calendar.getInstance();
        calendar.set(1900,Calendar.JANUARY,1);
        calendar.add(Calendar.DAY_OF_MONTH,times -2);
        Date date = calendar.getTime();
        return date;
    }

    /**
     * key;物料编码 val:物料相关信息(map)
     * @param materialList
     * @return
     */
    private Map<String,Object> changeMaterialToMap(List<Map<String,Object>> materialList){
        Map<String,Object> dataMap = new HashMap<>();
        for (Map<String,Object> data : materialList){
            String FNUMBER = VtuzxUtil.getString(data,"FNUMBER");
            String FNAME = VtuzxUtil.getString(data,"FNAME");
            String FSPECIFICATION = VtuzxUtil.getString(data,"FSPECIFICATION");
            String unitNo = VtuzxUtil.getString(data,"unitNo");//单位编码
            String unitName = VtuzxUtil.getString(data,"unitName");//单位名称
            String FDOCUMENTSTATUS = VtuzxUtil.getString(data,"FDOCUMENTSTATUS");//审核状态
            String FFORBIDSTATUS = VtuzxUtil.getString(data,"FFORBIDSTATUS");//禁用状态
            Map<String,Object> materialMap = new HashMap<>();
            materialMap.put("FNUMBER",FNUMBER);
            materialMap.put("FNAME",FNAME);
            materialMap.put("FSPECIFICATION",FSPECIFICATION);
            materialMap.put("unitNo",unitNo);
            materialMap.put("unitName",unitName);
            materialMap.put("FDOCUMENTSTATUS",FDOCUMENTSTATUS);
            materialMap.put("FFORBIDSTATUS",FFORBIDSTATUS);
            dataMap.put(FNUMBER,materialMap);
        }
        return dataMap;
    }
    /**
     * 校验销售订单导入的数据
     * @param user_id
     * @param map
     * @return
     * @throws Exception
     */
    private Boolean checkQingSfcInstock(String userName,Long user_id,List<Map<String,Object>> map) throws Exception{
        //添加行号
        int i = 3;
        for (Map<String,Object> data : map){
            data.put("line",i);
            i++;
        }
        //添加之前做一个删除
        materialService.deleteQingsfcInstockOrder(userName,user_id);
        //sqlserver数据库添加当前导入的数据
        materialService.saveQingSfcInstock(userName,user_id,map);
        //校验指令单号
        List<Map<String,Object>> checkQingMoNo =  materialService.checkQingInstockBillNo(user_id);
        //校验物料
        List<Map<String,Object>> checkQingMaterial =  materialService.checkQingInstockMaterial(user_id);
        //校验数量
        List<Map<String,Object>> checkQingInstockCount =  materialService.checkQingInstockCount(user_id);
        //校验数量
        List<Map<String,Object>> checkQingInstocksumcount =  materialService.checkQingInstocksumcount(user_id);
        //校验仓库
        List<Map<String,Object>> checkQingStock =  materialService.checkQingInstockStock(user_id);
        //校验仓位
        List<Map<String,Object>> checkQingLocation =  materialService.checkQingisLocation(user_id);


        //判断查询的数据如果都为空的话说明模板数据校验通过可以导入,如果不为空的话添加日志信息并且停止传单
        if (VtuzxUtil.isEmpty(checkQingMoNo) &&  VtuzxUtil.isEmpty(checkQingMaterial) && VtuzxUtil.isEmpty(checkQingInstockCount)&& VtuzxUtil.isEmpty(checkQingInstocksumcount)&& VtuzxUtil.isEmpty(checkQingStock) && VtuzxUtil.isEmpty(checkQingLocation)){
            return true;
        }  else {//有一个不等于空的就说明有问题,需要向日志中添加信息
            saveQingOperpLog(userName,user_id,checkQingMoNo,checkQingMaterial,checkQingInstockCount,checkQingInstocksumcount,checkQingStock,checkQingLocation);
            return false;
        }

    }
    /**
     * 模板级校验添加日志信息
     * @param checkQingMoNo
     * @param checkQingMaterial

     */
    private void saveQingOperpLog(String userName,Long user_id,List<Map<String,Object>> checkQingMoNo,List<Map<String,Object>> checkQingMaterial,List<Map<String,Object>> checkQingInstockCount,List<Map<String,Object>> checkQingInstocksumcount,
                              List<Map<String,Object>> checkQingStock,List<Map<String,Object>> checkQingLocation){
        String tbbillNo = qingSyncOrderService.startQingSyncOrder(userName,user_id,"生产入库单模板校验");
        List<QingSyncOrderDetail> orderDetailList = new ArrayList<>();
        if (!VtuzxUtil.isEmpty(checkQingMoNo)){//指令单号校验
            for (Map<String,Object> data : checkQingMoNo){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产入库单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的指令单号不允许为空、生产汇报单未生成、生产汇报单未审核");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingMaterial)){//物料校验
            for (Map<String,Object> data : checkQingMaterial){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产入库单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的物料编码未审核,或者不存在,或者已禁用,或者不允许生产请确认");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingInstockCount)){//校验数量
            for (Map<String,Object> data : checkQingInstockCount){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产入库单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的数量不能小于等于0,入库单数量不能大于汇报单数量");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingInstocksumcount)){//校验总和
            for (Map<String,Object> data : checkQingInstocksumcount){
                String MoBillNo = VtuzxUtil.getString(data, "MoBillNo").trim();//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产入库单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("制令单号"+MoBillNo+"的数量总入库单数量不能大于总汇报单数量");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingStock)){//开工时间
            for (Map<String,Object> data : checkQingStock){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产入库单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行仓库不能为空,仓库未审核,仓库被禁用，仓库不存在");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        if (!VtuzxUtil.isEmpty(checkQingLocation)){//完工时间
            for (Map<String,Object> data : checkQingLocation){
                int line = VtuzxUtil.getInt(data,"LINE");//行号
                QingSyncOrderDetail qingSyncOrderDetail = new QingSyncOrderDetail();
                qingSyncOrderDetail.setOrderNo("生产入库单模板级校验");//客户订单号
                qingSyncOrderDetail.setBillNo(tbbillNo);
                qingSyncOrderDetail.setCreateTime(new Date());
                qingSyncOrderDetail.setUpdateTime(new Date());
                qingSyncOrderDetail.setIsSuccess(false);
                qingSyncOrderDetail.setMessage("第" + line + "行的仓库未启用仓位、仓库启用仓位但未填写仓位值");
                orderDetailList.add(qingSyncOrderDetail);
            }
        }

        qingSyncOrderService.endQingSyncOrder(orderDetailList,tbbillNo);
    }

    @Override
    public Map<String, Object> deleteQingSfcInstock(String userName,Long user_id,Map<String, Object> map) throws Exception {
        String billNoList = map.get("moBillNo").toString();
        //根据逗号拆分成数组
        int headCount = 0;
        int detailCount =0;
        String[] split = billNoList.split(",");
        for (String idNo : split){
            QingSfcInstock qingSfcInstock = qingSfcInstockDao.selectById(idNo);
            String billNo = qingSfcInstock.getMoBillNo();
            VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginQKingdeeByUser(user_id);
            //查询金蝶生产订单
            List<VtuzxMap> prdcumQuery = vtuzxKingdeeService.query(client,"PRD_INSTOCK", new VtuzxArrayList<>(
                            "FMoBillNo"
                    ),
                    // 组合两个过滤条件（规格型号 + 物料分组）
                    String.format("FMoBillNo = '%s' ",
                            billNo), null, 0, 0);

            if (!VtuzxUtil.isEmpty(prdcumQuery)) {
                throw new RuntimeException(String.format("该订单已存在不能删除订单号%s", billNo));
            }
            // 删除本地数据库记录
            int deletedDetails = qingSfcInstockDao.delete(
                    new LambdaQueryWrapper<QingSfcInstock>()
                            .eq(QingSfcInstock::getMoBillNo, billNo)
            );
            headCount += deletedDetails;
            int deletedMain = qingSfcInstockDetailDao.delete(
                    new LambdaQueryWrapper<QingSfcInstockDetail>()
                            .eq(QingSfcInstockDetail::getBillNo, billNo)
            );
            detailCount += deletedMain;
        }
        Map<String, Object> data = new HashMap<>();
        data.put("success", true);
        data.put("message", String.format("主表删除 %d 条，明细表删除 %d 条", headCount, detailCount));
        return data;
    }




}
